package org.vacoor.nothing.security.controller;

import com.google.common.collect.ImmutableMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.vacoor.nothing.common.codec.Base62;
import org.vacoor.nothing.common.util.Oid;
import org.vacoor.nothing.common.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 */
@RequestMapping("/account")
public class AccountController {
    private static final int VERIFY_TYPE_EMAIL = 1;
    private static final int VERIFY_TYPE_MOBILE = 2;

    /* *********************************
     *             signup
     * *********************************/

    @RequestMapping("check")
    public Map<String, Object> check(String email) {
        HttpServletRequest request;
        // find user by email
        /*
            if email exists {
                if activated = 1 {

                } else {
                }
            }
         */
        return null;
    }

    @RequestMapping("send-signup-sms")
    public ImmutableMap<String, Object> sendSignupSms(String mobile) {
        if (!StringUtils.hasText(mobile)) {
            return ImmutableMap.<String, Object>of("success", false);
        }

        return null;
    }

    @RequestMapping("signup")
    public void signup() {}

    @RequestMapping(value = "signup", method = RequestMethod.POST)
    public void signup(String email, String mobile, String mcode, String password) {
        //
        if (StringUtils.hasText(mobile)) {
            // set mobile & and email
            return;
        }

        if (StringUtils.hasText(mobile)) {
            // validate mobile and verify code
        }

        // invalid request
    }

    @RequestMapping("create")
    public String create(int type) {
        // set activated = true
        if (type == VERIFY_TYPE_MOBILE) {
            /*
                // validate mobile & verify
                if verify not exists or is valid {
                   return 'invalid code'
                }

                if verify is expired {
                   return 'invalid code' or 'code is expired'
                }
             */
        }

        if (type == VERIFY_TYPE_EMAIL) {
            /*
                //
                set activated = false;
                send activate address to email
             */
        }

        /*
            save to db
         */

        return null;
    }

    /**
     * 重新发送激活邮件
     */
    @RequestMapping("resend-activate-email")
    public Map<String, Object> resendActivateEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return ImmutableMap.<String, Object>of("success", true, "error", "Invalid Request");
        } else {
            // do send email
            return ImmutableMap.<String, Object>of("success", true);
        }
    }

    @RequestMapping("/activate")
    public String activate(String username, String code, int a) {
        /*
          if code error
             invalid activate code
             resend active email
          else
             Your account has been activated.
             Click here to login to your account.
         */
        return "";
    }

    // http://vacoor.org/activate/ychwork@126.com/8738
    // 如果无法访问以上链接，请通过【激活码】：8738，于 XXX 登录界面（http://vacoor.org/activate-register）进行激活。
    // 申请时，只填写 email, 激活时填写昵称 密码?
    @RequestMapping(value = "activate", method = RequestMethod.GET)
    public void activate(String account, String safeKey) {
        try {
            Oid clientKey = StringUtils.hasText(safeKey) ? new Oid(Base62.decode(safeKey)) : null;
            Oid serverKey;
            /*
            User u = userService.findUser(account);
            safeKey = null != u ? u.getSafeKey() : null;
            */
            serverKey = StringUtils.hasText(safeKey) ? new Oid(Base62.decode(safeKey)) : null;

            int expired = 30 * 60;
            if (null == serverKey || !serverKey.equals(clientKey)) {
                // invalid safekey
                throw new InvalidSafeKeyException("safe key is invalid or expired");
            }

            if (new Date().getTime() / 1000 - serverKey.getTimestamp() > expired) {
                // expired
                throw new InvalidSafeKeyException("safe key is invalid or expired");
            }
        } catch (Throwable e) {
            throw e instanceof InvalidSafeKeyException ? (InvalidSafeKeyException) e : new InvalidSafeKeyException(e);
            // model.add("error", "验证码不合法或已经过期")
        }
    }

    @RequestMapping(value = "activate", method = RequestMethod.POST)
    public void activate(String account, String safeKey, String password, String confirmPassword) {
        // validate safeKey
        // delete db safe key
        // 修改成功, 验证码不合法或已经过期
    }


    /**
     * 发送手机注册验证码
     */
    @RequestMapping("sendRegSms")
    public Map<String, Object> sendRegSms(String mobile) {
        /*
            cache mobile - verify code
            send verify code to mobile;
         */
        return null;
    }

    /* *********************************
     *           forgot password
     * *********************************/

    @RequestMapping("forgot") // find, recovery
    public void forgot() {}

    @RequestMapping("send-sms")
    public Map<String, Object> sendSms() {
        return ImmutableMap.<String, Object>of("success", true);
    }

    @RequestMapping("check-sms")
    public Map<String, Object> checkMobile() {
        return null;
    }

    @RequestMapping(value = "recovery-mobile")
    public String recoveryByMobile(String verify) {
        System.out.println("find by mobile");
        // if (verify is )
        return "reset?code=8hYxMvJ0E/a3lmLnhurXAHRceOmrdysOIx33NeFnbl21tV2nhyfQnMeDWjjM3IW6A2sfaMhsUNrov3LYblvMHJV5aM8NUN57wV+js8D8OsdZMBxNAb4NS1lF4i7IjqfIaQarO0cGmoPGMYKWwdVMjniT1kCyXnSehAmv4KqbUL8=";
    }

    // @RequestMapping
    // public String recovery() {}
    @RequestMapping(value = "recovery-email")
    public String recoveryByEmail(String email) {
        // 验证邮件已发送至 <decode>tes***@qq.com</decode>，请登录邮箱查收！长时间未收到邮件，请再次发送，或查看垃圾邮箱。
        System.out.println("find by email");
        return null;
    }

    @RequestMapping("reset-password")
    public String reset(String safeKey) {
        return null;
    }

    /* ***********************************
     *           signin
     * ***********************************/

    @RequestMapping("signin")
    public String signin() {
        return null;
    }
}
